import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_app/api/api.dart' as api;
import 'package:flutter_app/bean/respon.dart';
import 'package:flutter_app/ui/pages/content.dart';
import 'package:flutter_app/ui/pages/find.dart';
import 'package:flutter_app/ui/pages/mySelf.dart';
import 'package:image_picker/image_picker.dart';
import 'package:transparent_image/transparent_image.dart';

class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => HomePageState();

  const HomePage();
}

class HomePageState extends State<HomePage> {
  final _title = <String>['首页信息', '信息分类', '用户信息'];
  var _titleText = '首页信息';
  var _page = 1;
  List<OneInfo> _list;
  var _pageController = new PageController();
  var _currentPageIndex = 0;
  String _bannerUrl = "";

  @override
  void initState() {
    super.initState();
    _refreshData();
  }

  @override
  void dispose() {
    super.dispose();
    api.clearOb();
  }

  void _refreshData() {
    api.getDataList(_setListData, _page);
    api.getBannerList(_setImage);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(_titleText),
      ),
      body: new PageView.builder(
          onPageChanged: _pageChange,
          controller: _pageController,
          itemCount: 3,
          itemBuilder: (BuildContext ctx, int index) {
            switch (index) {
              case 0:
                return _getListView();
              case 1:
                return const FindPage();
              case 2:
                return const MySelfPage();
            }
          }),
      bottomNavigationBar: new BottomNavigationBar(
          currentIndex: _currentPageIndex,
          onTap: (int index) {
            _pageController.animateToPage(index,
                duration: new Duration(seconds: 2),
                curve: new ElasticOutCurve(0.8));
            _pageChange(index);
          },
          items: [
            new BottomNavigationBarItem(
                icon: Icon(Icons.home), title: new Text("首页")),
            new BottomNavigationBarItem(
                icon: Icon(Icons.find_in_page), title: new Text("发现")),
            new BottomNavigationBarItem(
                icon: Icon(Icons.perm_identity), title: new Text("我的")),
          ]),
    );
  }

  void _pageChange(int index) {
    setState(() {
      if (_currentPageIndex != index) {
        _currentPageIndex = index;
        _titleText = _title[index];
      }
    });
  }

  Widget _getListView() {
    return new NotificationListener(
      child: new ListView.builder(
        itemCount: _list == null ? 0 : _list.length + 1,
        itemBuilder: (BuildContext context, int index) {
          if (index == 0) {
            return _getBanner();
          }
          return new GestureDetector(
              onTap: () {
                showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return _getDiaLog(index - 1);
                    });
              },
              child: _getListDataItem(_list, index));
        },
      ),
      onNotification: (OverscrollIndicatorNotification no) {
        if (no.leading) {
          _page = 1;
          _refreshData();
        } else {
          api.getDataList(_setListData, ++_page);
        }
      },
    );
  }

  Widget _getBanner() {
    if (_bannerUrl == "") {
      return new Container();
    }
    return new FadeInImage.memoryNetwork(
        height: 200.0, placeholder: kTransparentImage, image: _bannerUrl);
  }

  Widget _getDiaLog(int index) {
    return new AlertDialog(
      title: Text("温馨提示"),
      content: Text("跳转到信息内容"),
      actions: <Widget>[
        new FlatButton(
            onPressed: () {
              Navigator.of(context).pop();
              Navigator.push(context,
                  new MaterialPageRoute(builder: (BuildContext ctx) {
                return new ContentPage(_list[index]);
              }));
            },
            child: Text("确认")),
        new FlatButton(
            onPressed: () {
              Navigator.of(context).pop();
              _getImage();
            },
            child: Text("取消")),
      ],
    );
  }

  Widget _getListDataItem(List<OneInfo> list, int index) {
    return Card(
        child: Container(
      padding: const EdgeInsets.all(6.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          new Text("标题:" + list[index - 1].title),
          new Text("作者:" + list[index - 1].author),
          new Text("信息内容:\n" + list[index - 1].desc),
        ],
      ),
    ));
  }

  Future _getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    var readAsBytes = await image.readAsBytes();
    var encode = base64.encode(readAsBytes);
    print(encode);
  }

  void _setListData(dynamic list) {
    setState(() {
      if (_page == 1) {
        this._list = list;
      } else if (list.length <= 0) {
        _page--;
      } else {
        this._list.addAll(list);
      }
    });
  }

  void _setImage(dynamic url) {
    setState(() {
      _bannerUrl = url;
    });
  }
}
